﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.Mvc;

namespace MvcImproved.Generic.Controls
{
	public interface IArrayIndexed
	{
		string IndexSuffix
		{
			get;
		}
	}

	[ParseChildren(true)]
	[PersistChildren(true)]
	public class RepeaterItem<TMemberValueInstance, TArrayIndexMemberValue> : TypedContainer<TMemberValueInstance>, IDataItemContainer, IArrayIndexed
	{
		private TArrayIndexMemberValue _ArrayIndexValue;
		private int _ItemIndex;
		private Boolean _UseItemIndexForSuffix;

		public RepeaterItem(int itemIndex, TMemberValueInstance dataItem, TArrayIndexMemberValue arrayIndexValue, bool useItemIndexForSuffix)
			: base(dataItem)
		{
			_ItemIndex = itemIndex;
			_ArrayIndexValue = arrayIndexValue;
			_UseItemIndexForSuffix = useItemIndexForSuffix;
		}

		object IDataItemContainer.DataItem
		{
			get
			{
				return _DataItem;
			}
		}

		public int DataItemIndex
		{
			get
			{
				return _ItemIndex;
			}
		}

		public int DisplayIndex
		{
			get
			{
				return _ItemIndex;
			}
		}

		public string IndexSuffix
		{
			get
			{
				if (_UseItemIndexForSuffix)
					return String.Format("[{0}]", _ItemIndex);
				else
					return String.Format("[{0}]", _ArrayIndexValue);
			}
		}

		public string CssClass;
		public HtmlTextWriterTag Wrapper = HtmlTextWriterTag.Unknown;

		protected override void Render(HtmlTextWriter writer)
		{
			if (Wrapper != HtmlTextWriterTag.Unknown)
			{
				if ( ! String.IsNullOrEmpty(CssClass) )
					writer.AddAttribute("class", CssClass);
				writer.RenderBeginTag(Wrapper);
			}

			base.Render(writer);

			if (Wrapper != HtmlTextWriterTag.Unknown)
				writer.RenderEndTag();
		}
	}
}
